!function ($) {
    var ProgressBar = function (element, options) {
        this.target_el = "#" + element.id;
        if (options) _.extend(this, options);
    };

    ProgressBar.prototype = {
        constructor:ProgressBar,
        text: "Loading...",
        pollingInterval: 100,

        Start: function(urlForText) {
            var text = this.text;
            if (urlForText) text = "Downloading Data from '<a href='" + urlForText + "' target='_blank'>" + urlForText + "</a>'...";

            var pid = ("id_" + Math.random()).replace(".", "");

            var html = "";
            html += "<div id='" + pid + "'>";
            if (text) {
                html += "<span>" + text + "</span>";
            }
            html += "<div class='progress progress-striped active'>";
            html += "<div class='bar' style='width: 0%;'></div>";
            html += "</div>";
            html += "</div>";
            $(this.target_el).append(html);

            var intervalFn = function() {
                var currentWidth = $("#" + pid + " .bar").width();
                var newwidth = 40;
                if (currentWidth) {
                    if (currentWidth >= 400) {
                        newwidth = 0;
                    } else {
                        newwidth = currentWidth + 100;
                    }
                }
                $("#" + pid + " .bar").width(newwidth);
            };

            var _interval = setInterval(intervalFn, this.pollingInterval);
            return function() {
                if (_interval) clearInterval(_interval);
                $("#" + pid).remove();
            };
        }
    };

    // jQuery Plugin
    $.fn.progressbar = function (options) {
        var pb;
        this.each(function () {
            var $this = $(this);
            var ft = $this.data("ProgressBar");
            if (!ft) $this.data("ProgressBar", (ft = new ProgressBar(this, options)));
            pb = ft.Start(options ? options["urlForText"] : null);
        });
        return pb;
    };
}(window.jQuery);